
#include "imagelib.h"

bool ILimage::InitLibraray()
{
	ilInit();
	iluInit();
	ilutInit();

	ilutRenderer( ILUT_OPENGL );
	return true;
}

bool ILimage::LoadFile( const TCHAR* filename )
{
	ILint id = ilGenImage();
	ilBindImage( id );

	ILstring s;
	s = const_cast<TCHAR*>( filename );
	if( iluLoadImage( s ) ){
		m_imageInfo.Data = ilGetData();
		m_imageInfo.Width = ilGetInteger( IL_IMAGE_WIDTH);
		m_imageInfo.Height = ilGetInteger( IL_IMAGE_HEIGHT);
		m_imageInfo.Bpp = ilGetInteger( IL_IMAGE_BPP );
		m_imageInfo.Origin = ilGetInteger( IL_IMAGE_ORIGIN );
		m_imageInfo.CubeFlags = ilGetInteger( IL_IMAGE_CUBEFLAGS );
		m_imageInfo.Depth = ilGetInteger( IL_IMAGE_DEPTH );
		m_imageInfo.Format = ilGetInteger( IL_IMAGE_FORMAT );
		m_imageInfo.Type = ilGetInteger( IL_IMAGE_FORMAT );
		m_imageInfo.Id = id;
		m_imageInfo.NumLayers = ilGetInteger( IL_NUM_LAYERS );
		m_imageInfo.NumMips = ilGetInteger( IL_IMAGE_TYPE );
		m_imageInfo.NumNext = 0;// ?
		m_imageInfo.SizeOfData = ilGetInteger( IL_IMAGE_SIZE_OF_DATA );
		m_imageInfo.Palette = ilGetPalette();
		m_imageInfo.PalSize = ilGetInteger( IL_PALETTE_SIZE );
		m_imageInfo.PalType = ilGetInteger( IL_PALETTE_TYPE );

	//	iluGetImageInfo(&m_imageInfo);
		m_fileName = const_cast<TCHAR*>( filename );
		return true;
	}
	m_fileName = _T("");
	memset( &m_imageInfo,0,sizeof(ILinfo));
	return false;
}

void ILimage::Free()
{
	ilDeleteImage(m_imageInfo.Id);
	m_fileName = _T("");
	memset( &m_imageInfo,0,sizeof(ILinfo));
}

ILimage::ILimage()
{
	m_fileName = _T("");
	memset( &m_imageInfo,0,sizeof(ILinfo));
}
int ILimage::GetWidth()
{
	return m_imageInfo.Width;
}

int ILimage::GetHeight()
{
	return m_imageInfo.Height;
}

int ILimage::GetBpp()
{
	return m_imageInfo.Bpp;
}

unsigned char* ILimage::GetData()
{
	return m_imageInfo.Data;
}

inline
float ILimage::GetPointHeight(int x,int y)
{
	const int m_width	=	m_imageInfo.Width;
	const int m_height	=	m_imageInfo.Height;
	int rx = (x+m_width/2);
	int ry = (y+m_height/2);

	if(rx<0 || ry<0 || rx>m_width || ry>m_height)
		return 1.0f;

	GLfloat fRet = m_imageInfo.Data[rx*m_width + ry]/4.0f;
	return fRet;
}

GLbbox ILimage::GetBoundingBox(RECT& rc)
{
	GLbbox bbox;
	GLvec3f p1,p2;
	GLfloat min = 0.0f,max = 0.0f;

	for(int i=rc.left;i<=rc.right-1;i++)
	{
		for(int j=rc.bottom;j<=rc.top;j++)
		{
			GLfloat fHeight = GetPointHeight(i,j);
			min = fHeight>min?min:fHeight;
			max = fHeight>max?fHeight:max;
		}
	}
	
	p1.x = rc.left;p1.y = min;p1.z = rc.bottom;
	p2.x = rc.right;p2.y = max;p2.z = rc.top;

	bbox.AddVertex(p1);bbox.AddVertex(p2);

	return bbox;
}